package suncertify.util;

import java.util.*;
import java.io.*;
import java.text.MessageFormat;

/**
 * This class provides implementation of options managing.
 * Properties is loaded and saved from/to static property file
 */
public class Options {
    private static final Options instance = new Options();
    private static final String LINE_PATTERN = "{0}={1}\n";
    private static final String RES_PATH = "suncertify.properties";
    private Map<String, String> props = new HashMap<String, String>();

    public static final String LOCAL_DB_FILE = "db.local.path";
    public static final String REMOTE_DB_FILE = "db.remote.path";
    public static final String SERVER_IP = "server.remote.ip";

    /**
     * returns instance of Options class
     * @return instance
     */
    public static Options getInstance() {
        return instance;
    }

    private Options() {
        load();
    }

    /**
     * returns value of option
     * @param key option key
     * @return option value
     */
    public String get(String key) {
        return props.get(key);
    }

    /**
     * set option value
     * @param key option key
     * @param value option value
     */
    public void set(String key, String value) {
        props.put(key, value);
    }

    /**
     * saves the options to local file system
     */
    public synchronized void save() {
        if (props.size() == 0) {
            return;
        }
        FileWriter w = null;
        try {
            w = new FileWriter(RES_PATH);
            Set<String> keys = props.keySet();
            for (String key : keys) {
                String line = MessageFormat.format(LINE_PATTERN, key, props.get(key));
                w.write(line.replace("\\", "\\\\"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (w != null) {
                try {
                    w.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void load() {
        FileInputStream fis = null;
        if (!props.isEmpty()) {
            props.clear();
        }
        try {
            fis = new FileInputStream(RES_PATH);
            ResourceBundle res = new PropertyResourceBundle(fis);
            Set<String> keys = res.keySet();
            for (String key : keys) {
                props.put(key, res.getString(key));
            }
        } catch (IOException e) {
            //do nothing, property file not found
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
